import socket
import os
server = socket.socket()
server.bind(("localhost", 8080))
server.listen()
while True:
    print("waiting for client.....")
    conn, addr = server.accept()
    while True:
        try:  # windows 客户端断开时会报异常,这里捕获程序继续执行
            data = conn.recv(1024)
            if not data:
                print("客户端断开了")
                break
        except Exception as e:
            print("客户端异常:", e)
            break
        print("接受到命令:", data)
        # os.popen: 打开一个命令通道,返回一个命令结果的文件对象
        res = os.popen(data.decode()).read()
        print(res)
        if len(res) == 0:
            res = "命令无返回值"
        # 先告诉客户端数据有多大
        conn.send(str(len(res)).encode("utf-8"))
        print("等待客户ack应答...")
        client_final_ack = conn.recv(1024)  # 等待客户端响应.避免连续发送产生粘包问题
        print("客户应答:", client_final_ack.decode())
        print(type(res))
        conn.sendall(res.encode())  # 发送端也有最大数据量限制,所以这里用sendall,相当于重复循环调用conn.send,直至数据发送完毕
server.close()


